package com.atguigu4.connection;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;

/**
 * DBCP数据库连接池
 * @auther user
 * @date 2021/12/10 - 3:59
 */
public class DBCPTest {
    //方式一
    @Test
    public void testGetConnection() throws Exception{
        //创建DBCP数据库连接池
        BasicDataSource source = new BasicDataSource();
        //设置基本信息
        source.setDriverClassName("com.mysql.jdbc.Driver");
        source.setUrl("jdbc:mysql://8.130.54.82:3306/test");
        source.setUsername("root");
        source.setPassword("hwychu1998917Aa");
        //设置连接池基本属性
        source.setInitialSize(5);//初始化连接数
        source.setMaxActive(10);//最大活跃数

        Connection connection = source.getConnection();
        System.out.println("connection = " + connection);
    }
    //方式二：使用配置文件 dbcp.properties
    @Test
    public void testGetConnection1() throws Exception{
        //加载配置文件
        Properties properties = new Properties();
        //方式一；
        //InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("dbcp.properties");
        //方式二
        FileInputStream inputStream = new FileInputStream(new File("src/dbcp.properties"));
        properties.load(inputStream);
        DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
        Connection connection = dataSource.getConnection();
        System.out.println("connection = " + connection);
    }

}
